#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/time.h>
 
#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

#include "system_entity.h"

#include "user_define.h"
#include "tcm_constants.h"
#include "tcm_structures.h"
#include "tcmfunc.h"
#include "tcm_cube_struct.h"
#include "tcm_key_manage.h"
#include "tcm_key_desc.h"
#include "tcm_pik_desc.h"
#include "pik_usercheck.h"
// add para lib_include
int pik_usercheck_init(void * sub_proc, void * para)
{
	int ret;
	// add yorself's module init func here
	return 0;
}
int pik_usercheck_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here
	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			ex_module_sendmsg(sub_proc,recv_msg);
			continue;
		}
		if((type==TYPE(GENERAL_RETURN))&&(subtype==SUBTYPE(GENERAL_RETURN,STRING)))
		{
            		ret=proc_keyevent_cmd(sub_proc,recv_msg);
		}
        else
			ex_module_sendmsg(sub_proc,recv_msg);
	}
	return 0;
}

int proc_keyevent_cmd(void * sub_proc,void * recv_msg)
{
	int ret;
    MSG_HEAD * msg_head;
	RECORD(GENERAL_RETURN,STRING) * keyevent_cmd;
	ret=message_get_record(recv_msg,&keyevent_cmd,0);
	if(ret<0)
		return ret;
    
    if(Strcmp(keyevent_cmd->name,"pik_gen")==0)
    {
            return proc_pik_usercheck(sub_proc,keyevent_cmd,recv_msg);
    }
    return ex_module_sendmsg(sub_proc,recv_msg);
}

int proc_pik_usercheck(void * sub_proc,RECORD(GENERAL_RETURN,STRING) * keyevent_cmd,void * recv_msg)
{
    int ret; 
    RECORD(TCM_PIK_DESC,USERINFO) * pik_userinfo;
    RECORD(USER_DEFINE,SERVER_STATE) * server_state;
    char user_name[DIGEST_SIZE];
    MSG_EXPAND * msg_expand;
	

    // judge if this message is already has instance_info , if it has,then send this message
    ret = message_get_define_expand(recv_msg,&msg_expand,TYPE_PAIR(TCM_PIK_DESC,USERINFO));
    if(ret<0)
        return -EINVAL;
    if(msg_expand == NULL)
    {
	    return -EINVAL;
    }
    pik_userinfo=msg_expand->expand;

    print_cubeaudit("enter pik_usercheck function!");

    // compare pikreq's user role with server_state's role

    DB_RECORD * db_record;
    db_record = memdb_find_first(TYPE_PAIR(USER_DEFINE,SERVER_STATE),"user_name",pik_userinfo->username);
    if(db_record == NULL)
	    return -EINVAL;
    server_state = db_record->record;

    printf("userinfo role is %s server_state role is %d \n",pik_userinfo->user_role,server_state->role);

    ret=ex_module_sendmsg(sub_proc,recv_msg);
    return ret;
}
